package com.sensePlusVR.manager;

import java.util.ArrayList;

import org.apache.http.Header;
import org.json.JSONObject;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.RequestParams;
import com.sensePlusVR.application.VRApplication;
import com.sensePlusVR.bean.ActorItem;
import com.sensePlusVR.bean.BuriePointEventReqDto;
import com.sensePlusVR.bean.BuriedPointFollowData;
import com.sensePlusVR.bean.CollectFollowIds;
import com.sensePlusVR.bean.ServerErrorMsg;
import com.sensePlusVR.net.NetCallBack;
import com.sensePlusVR.net.NetRequestManager;
import com.sensePlusVR.net.RequestUtils;
import com.sensePlusVR.utils.Constant;
import com.sensePlusVR.utils.ConstantURL;
import com.sensePlusVR.utils.DateTimeUtil;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.MySharedPreferences;
import com.sensePlusVR.utils.UserUtil;

@SuppressWarnings("deprecation")
public class CollectionFollowManager extends BaseManager{
	
	public static final int EventFollowAdded = 0;
	public static final int EventFollowDeled = 1;
	public static final int EventCollectionAdded = 2;
	public static final int EventCollectionDeled = 3;
	public static final int EventFollowCollectionGot = 4;
	public static final int EventColloctionedDownload = 5;
	
	public static final int EventErrorBase = 100;
	
	private static final int FollowAdd = 1;
	private static final int FollowDel = 2;
	private static final int ColloctionAdd = 3;
	private static final int ColloctionDel = 4;
	private static final String TAG = CollectionFollowManager.class.getSimpleName();
	private static CollectionFollowManager INSTANTS;
	
	
	static public CollectionFollowManager getInstants(){
		if (INSTANTS == null){
			INSTANTS = new CollectionFollowManager();
		}
		return INSTANTS;
	}
	
	private class callbackThread extends Thread{
		private int event;
		private int resId;
		public callbackThread(int event, int resId){
			this.event = event;
			this.resId = resId;
		}
		@Override
		public void run() {
			callEventListener(event, Integer.valueOf(resId));
		}
	}
	
	private void callbackInThread(int event, int resId){
		callbackThread th = new callbackThread(event, resId);
		th.start();
	}
	
	
	private void setLocalRecoder(int action, int resId, boolean needcallback){
		CollectFollowIds cf = (CollectFollowIds)MySharedPreferences.getObject(VRApplication.getAppContext(), Constant.USER_FOLLOW_IDS,CollectFollowIds.class);
		int event = -1;
		if (cf == null){
			cf = new CollectFollowIds();
			ArrayList<Integer> list = new ArrayList<Integer>();
			list.add(resId);
			if (action == ColloctionAdd)
				cf.setCollectionList(list);
			if (action == FollowAdd)
				cf.setFollowList(list);
			return;
		}
		ArrayList<Integer> list;
		if (action == ColloctionAdd){
			list = cf.getCollectionList();
			if (list != null && !list.contains(Integer.valueOf(resId))){
				list.add(Integer.valueOf(resId));
				event = EventCollectionAdded;
				//callbackInThread(EventCollectionAdded, resId);
			}

			
			
		}else if (action == ColloctionDel){
			list = cf.getCollectionList();
			if (list != null && list.contains(Integer.valueOf(resId))){
				list.remove(Integer.valueOf(resId));
				event = EventCollectionDeled;
				//callbackInThread(EventCollectionDeled, resId);
			}
		}else if (action == FollowAdd){
			list = cf.getFollowList();
			if (list != null && !list.contains(Integer.valueOf(resId))){
				list.add(Integer.valueOf(resId));
				event = EventFollowAdded;
				//callbackInThread(EventFollowAdded, resId);
			}
		}else if (action == FollowDel){
			list = cf.getFollowList();
			if (list != null && list.contains(Integer.valueOf(resId))){
				event = EventFollowDeled;
				//callbackInThread(EventFollowDeled, resId);
				list.remove(Integer.valueOf(resId));
			}
		}
		if (event != -1){
			MySharedPreferences.saveObject(VRApplication.getAppContext(), Constant.USER_FOLLOW_IDS, cf);
			if (needcallback)
				callbackInThread(event, resId);
		}
	}
	
	public CollectFollowIds getFollowsAndCollections(int userId, boolean forced){
		CollectFollowIds collectFollowIds = (CollectFollowIds)MySharedPreferences.getObject(VRApplication.getAppContext(), Constant.USER_FOLLOW_IDS,CollectFollowIds.class);
		
		MyLog.d(TAG, "CollectFollowIds --- getFollowsAndCollections");
		if (collectFollowIds == null) {
			MyLog.d(TAG, "CollectFollowIds getFollowsAndCollections");
			DownloadTask task = new DownloadTask(userId);
			task.start();
			return null;
		}else {
			if (forced){
				DownloadTask task = new DownloadTask(userId);
				task.start();				
			}
			return (collectFollowIds);
		}
	}
	
	public void FollowAdd(int userId, int resId){
		setLocalRecoder(FollowAdd, resId, true);
		
		UploadTask task = new UploadTask(userId, resId, FollowAdd);
		task.start();
	}
	
	public void FollowDel(int userId, int resId){
		setLocalRecoder(FollowDel, resId, true);
		
		UploadTask task = new UploadTask(userId, resId, FollowDel);
		task.start();
	} 
	public void CollectionAdd(int userId, int resId){
		setLocalRecoder(ColloctionAdd, resId, true);
		
		UploadTask task = new UploadTask(userId, resId, ColloctionAdd);
		task.start();
	}
	
	public void CollectionDel(int userId, int resId){
		setLocalRecoder(ColloctionDel, resId, true);
		
		UploadTask task = new UploadTask(userId, resId, ColloctionDel);
		task.start();
	}
	
	//仅仅回调，为了通知在已经收藏情况下在VideoDetail中点击下载，通知Collection列表刷新排序
	public void CollectionedDownload(int userId, int resId){
		callbackInThread(EventColloctionedDownload, resId);
	}
	
	
	public class DownloadTask{
		private int userId;
		public DownloadTask(int userId){
			this.userId = userId;
		}
		
		public void start(){
			RequestParams params = new RequestParams();
			params.put("userid", userId);
			
			String token = MySharedPreferences.getString2(VRApplication.getAppContext(),MySharedPreferences.NAME_NOT_CLEAR, Constant.LOGIN_SUCCESS_TOKEN);
			MyLog.d(TAG, "token getMyGameListIds : " + token);
			RequestUtils.clientToken.addHeader(Constant.STR_X_AUTH_TOKEN,token);
			final String url = ConstantURL.GET_COLLECTION_FOLLOW_IDS;
			RequestUtils.clientTokenGet(VRApplication.getAppContext(),url, params, new NetCallBack(){
				@Override
				public void onMySuccess(int statusCode, Header[] aheader,
						JSONObject jsonobject) {
					super.onMySuccess(statusCode, aheader, jsonobject);
					MyLog.d(TAG, "getMyGameListIds onMySuccess statusCode : "
							+ statusCode);
					if(jsonobject == null){
						MyLog.d(TAG, "getMyGameListIds jsonobject == null");
						return;
					}
					MyLog.d(TAG, "getMyGameListIds onMySuccess jsonobject : "
							+ jsonobject.toString());
					
					if (statusCode == 200) {
						//ServerErrorMsg msg = JSON.parseObject(jsonobject.toString(), ServerErrorMsg.class);
						//if(msg.getError().equals(getActivity().getResources().getString(R.string.msg_success_key_E000))){
						MyLog.d(TAG, "getMyGameListIds success");
						CollectFollowIds collectFollowIds = JSON.parseObject(jsonobject.toString(), CollectFollowIds.class);
						MyLog.d(TAG, "getMyGameListIds collectFollowIds :" + collectFollowIds.toString());
						//ArrayList<Integer> collectionList = collectFollowIds.getCollectionList();
						//getMyCollectionGameList(collectionList);
						MySharedPreferences.saveObject(VRApplication.getAppContext(), Constant.USER_FOLLOW_IDS, collectFollowIds);
						//NotifyUser3(collectFollowIds);
						//ActorManager.getInstants().getFollowActors(collectFollowIds.getFollowList());
						callEventListener(EventFollowCollectionGot, collectFollowIds);
						return;
					}
					MyLog.e(TAG, "getMyGameListIds failed");
				}
				
				@Override
				public void onMyFailure(int statusCode, Header[] headers,
						Throwable throwable, JSONObject errorResponse) {
					super.onMyFailure(statusCode, headers, throwable, errorResponse);
					NetRequestManager.isCommonErr(statusCode, errorResponse, VRApplication.getAppContext(),url);
					if(throwable != null){
						MyLog.d(TAG, "throwable : " + throwable.getMessage());
					}
					
					MyLog.e(TAG, "onMyFailure statusCode : " + statusCode);
	    	        if(statusCode == 0 || errorResponse == null){
	    	        	MyLog.e(TAG, "onMyFailure errorJsonobject == null");
	    	        	return ;
	    	        }
	    	        MyLog.e(TAG, "error errorResponse : " + errorResponse.toString());
				}
			});

		}
	}
	
	
	public class UploadTask{
		private int userId;
		private int resId;
		private int action;
		public UploadTask(int userId, int resId, int action){
			this.userId = userId;
			this.resId = resId;
			this.action = action;
		}
		
		public void start(){
			switch(action){
			case FollowAdd:
				FollowAdd();
				break;
			case FollowDel:
				FollowDel();
				break;
			case ColloctionAdd:
				ColloctionAdd();
				break;
			case ColloctionDel:
				ColloctionDel();
				break;
			}


		}
		private void FollowDel(){
			final BuriePointEventReqDto buriePointEventReqDto = new BuriePointEventReqDto();
			final long timeL = System.currentTimeMillis();
			final long startTimeL = timeL;
			
			
			final String url = ConstantURL.FOLLOW_CANCEL_SINGLE + "actorid=" + resId + "&userid=" + userId;
			MyLog.d(TAG, "cancelFollow url : " + url);
		
			String token = MySharedPreferences.getString2(VRApplication.getAppContext(),MySharedPreferences.NAME_NOT_CLEAR, Constant.LOGIN_SUCCESS_TOKEN);
			MyLog.d(TAG, "token cancelFollow : " + token);
			RequestUtils.clientToken.addHeader(Constant.STR_X_AUTH_TOKEN,token);

			RequestUtils.clientTokenPut(VRApplication.getAppContext(), url, new NetCallBack(){
				@Override
				public void onMyStart() {
					super.onMyStart();
					MyLog.d(TAG, "cancelFollow onMyStart...");
				}
				
				@Override
				public void onMySuccess(int statusCode, Header[] aheader,
						JSONObject jsonobject) {
					super.onMySuccess(statusCode, aheader, jsonobject);
					if(jsonobject == null){
						MyLog.e(TAG, "cancelFollow onMySuccess jsonobject == null");
						return;
					}
					
					MyLog.d(TAG, "cancelFollow onMySuccess jsonobject : " + jsonobject.toString());
					
					if (statusCode == 200) {
						ServerErrorMsg msg = JSON.parseObject(jsonobject.toString(), ServerErrorMsg.class);
						if(msg.getError().equals(Constant.SERVER_SUCCESS_KEY_E000)){
							//DownloadTask task = new DownloadTask(userId);
							//task.start();
							buriedPointSuccess();
							MyLog.d(TAG, "follow cancel completed");
							return;
						}
					}
				}
				
				@Override
				public void onMyFailure(int statusCode, Header[] headers,
						Throwable throwable, JSONObject errorResponse) {
					super.onMyFailure(statusCode, headers, throwable, errorResponse);
					setLocalRecoder(FollowAdd, resId, false);
					callEventListener(EventErrorBase+EventFollowDeled, Integer.valueOf(resId));
					NetRequestManager.isCommonErr(statusCode, errorResponse, VRApplication.getAppContext(),url);
					
					buriedPointFail();
				}
				
				private void buriedPointStart() {
					buriePointEventReqDto.setUid(UserUtil.getUserId());
					buriePointEventReqDto.setEvent(Constant.BURIED_GAME_FOLLOW_CANCEL);
					
					BuriedPointFollowData buriedPointFollowData = new BuriedPointFollowData();
					ActorItem actorItem = ActorItem.getActorById(resId);
					if(actorItem != null){
						buriedPointFollowData.setName(actorItem.getName());
						buriedPointFollowData.setAge(actorItem.getAge());
						buriedPointFollowData.setStyle(actorItem.getStyle());
						buriedPointFollowData.setArea(actorItem.getArea());
						buriedPointFollowData.setActorId(actorItem.getId());
						buriedPointFollowData.setCompany(actorItem.getCompany());
						buriedPointFollowData.setWeight(actorItem.getWeight());
						buriedPointFollowData.setHeight(actorItem.getHeight());
						buriedPointFollowData.setBwh(actorItem.getBwh());
						buriedPointFollowData.setBirthday(actorItem.getBirthday());
						buriedPointFollowData.setHair(actorItem.getHair());
						buriedPointFollowData.setEyes(actorItem.getEyes());
						buriedPointFollowData.setEthnicity(actorItem.getEthnicity());
						buriedPointFollowData.setLanguage(actorItem.getLanguage());
					}
					buriePointEventReqDto.setData(JSON.toJSONString(buriedPointFollowData));
					
					String timeStr = DateTimeUtil.getStandTime(timeL);
					buriePointEventReqDto.setEvent_time(timeStr);
					
					buriePointEventReqDto.setStart_time(timeL);
					
					buriePointEventReqDto.setMode(ConstantURL.BURIED_MODE);
					
					BuriePointEventReqDto.saveOrUpdate(buriePointEventReqDto);
				}
				
				private void buriedPointSuccess() {
					buriedPointStart();
					long endTimeL = System.currentTimeMillis();
					long duration = endTimeL - startTimeL;
					buriePointEventReqDto.setDuration(duration);
					buriePointEventReqDto.setEnd_time(endTimeL);
					buriePointEventReqDto.setFlag(Constant.BURIED_FLAG_SUCCESS);
					buriePointEventReqDto.setState(Constant.BURIED_STATE_SUCCESS);
					BuriePointEventReqDto.saveOrUpdate(buriePointEventReqDto);
				}

				private void buriedPointFail() {
					buriedPointStart();
					long endTimeL = System.currentTimeMillis();
					long duration = endTimeL - startTimeL;
					buriePointEventReqDto.setDuration(duration);
					buriePointEventReqDto.setEnd_time(endTimeL);
					buriePointEventReqDto.setFlag(Constant.BURIED_FLAG_FAIL);
					buriePointEventReqDto.setState(Constant.BURIED_STATE_SUCCESS);
					BuriePointEventReqDto.saveOrUpdate(buriePointEventReqDto);
				}
			});
		}
		
		private void FollowAdd(){
			//埋点信息初始化
			final BuriePointEventReqDto buriePointEventReqDto = new BuriePointEventReqDto();
			final long timeL = System.currentTimeMillis();
			final long startTimeL = timeL;
			
			RequestParams params = new RequestParams();
			params.put("userid", userId);
			params.put("actorid", resId);
			
			final String url = ConstantURL.FOLLOW_SAVE_SINGLE;
			MyLog.d(TAG, "uploadlFollow url : " + url);
			
			String token = MySharedPreferences.getString2(VRApplication.getAppContext(),MySharedPreferences.NAME_NOT_CLEAR, Constant.LOGIN_SUCCESS_TOKEN);
			MyLog.d(TAG, "token uploadlFollow : " + token);
			RequestUtils.clientToken.addHeader(Constant.STR_X_AUTH_TOKEN,token);
			 
			RequestUtils.clientTokenPost(VRApplication.getAppContext(),url,params,new NetCallBack(){
				
				@Override
				public void onMyStart() {
					super.onMyStart();
					MyLog.d(TAG, "addFollow onMyStart...");
				}
				
				@Override
				public void onMySuccess(int statusCode, Header[] aheader,
								JSONObject jsonobject) {
							super.onMySuccess(statusCode, aheader, jsonobject);
							MyLog.d(TAG, "uploadlFollow onMySuccess statusCode : "
									+ statusCode);
							if(jsonobject == null){
								MyLog.d(TAG, "uploadlFollow jsonobject == null");
								return;
							}
							MyLog.d(TAG, "uploadlFollow onMySuccess jsonobject : "
									+ jsonobject.toString());
							
							if (statusCode == 200) {
								ServerErrorMsg msg = JSON.parseObject(jsonobject.toString(), ServerErrorMsg.class);
								if(msg.getError().equals(Constant.SERVER_SUCCESS_KEY_E000)){
									//MyToast.showMessage(context,R.string.collection_success);
									//DownloadTask task = new DownloadTask(userId);
									//task.start();
									
									buriedPointSuccess();
									
									MyLog.d(TAG, "follow addition completed");
									return;
								}
							}
							//MyToast.showMessage(context, R.string.collection_failed);
							MyLog.d(TAG, "follow addition failed");
						}

				@Override
				public void onMyFailure(int statusCode, Header[] headers,
						Throwable throwable, JSONObject errorResponse) {
					super.onMyFailure(statusCode, headers, throwable, errorResponse);
					//MyToast.showMessage(context, R.string.collection_failed);
					setLocalRecoder(FollowDel, resId, false);
					callEventListener(EventErrorBase + EventFollowAdded, Integer.valueOf(resId));
					NetRequestManager.isCommonErr(statusCode, errorResponse, VRApplication.getAppContext(),url);
					
					buriedPointFail();
				}
				
				private void buriedPointStart() {
					buriePointEventReqDto.setUid(UserUtil.getUserId());
					buriePointEventReqDto.setEvent(Constant.BURIED_GAME_FOLLOW_ADD);
					
					BuriedPointFollowData buriedPointFollowData = new BuriedPointFollowData();
					ActorItem actorItem = ActorItem.getActorById(resId);
					if(actorItem != null){
						buriedPointFollowData.setName(actorItem.getName());
						buriedPointFollowData.setAge(actorItem.getAge());
						buriedPointFollowData.setStyle(actorItem.getStyle());
						buriedPointFollowData.setArea(actorItem.getArea());
						buriedPointFollowData.setActorId(actorItem.getId());
						buriedPointFollowData.setCompany(actorItem.getCompany());
						buriedPointFollowData.setWeight(actorItem.getWeight());
						buriedPointFollowData.setHeight(actorItem.getHeight());
						buriedPointFollowData.setBwh(actorItem.getBwh());
						buriedPointFollowData.setBirthday(actorItem.getBirthday());
						buriedPointFollowData.setHair(actorItem.getHair());
						buriedPointFollowData.setEyes(actorItem.getEyes());
						buriedPointFollowData.setEthnicity(actorItem.getEthnicity());
						buriedPointFollowData.setLanguage(actorItem.getLanguage());
					}
					buriePointEventReqDto.setData(JSON.toJSONString(buriedPointFollowData));
					
					String timeStr = DateTimeUtil.getStandTime(timeL);
					buriePointEventReqDto.setEvent_time(timeStr);
					
					buriePointEventReqDto.setStart_time(timeL);
					
					buriePointEventReqDto.setMode(ConstantURL.BURIED_MODE);
					
					BuriePointEventReqDto.saveOrUpdate(buriePointEventReqDto);
				}
				
				private void buriedPointSuccess() {
					buriedPointStart();
					long endTimeL = System.currentTimeMillis();
					long duration = endTimeL - startTimeL;
					buriePointEventReqDto.setDuration(duration);
					buriePointEventReqDto.setEnd_time(endTimeL);
					buriePointEventReqDto.setFlag(Constant.BURIED_FLAG_SUCCESS);
					buriePointEventReqDto.setState(Constant.BURIED_STATE_SUCCESS);
					BuriePointEventReqDto.saveOrUpdate(buriePointEventReqDto);
				}

				private void buriedPointFail() {
					buriedPointStart();
					long endTimeL = System.currentTimeMillis();
					long duration = endTimeL - startTimeL;
					buriePointEventReqDto.setDuration(duration);
					buriePointEventReqDto.setEnd_time(endTimeL);
					buriePointEventReqDto.setFlag(Constant.BURIED_FLAG_FAIL);
					buriePointEventReqDto.setState(Constant.BURIED_STATE_SUCCESS);
					BuriePointEventReqDto.saveOrUpdate(buriePointEventReqDto);
				}
			});

		}

		private void ColloctionAdd(){
			MyLog.d(TAG, "uploadCollection userId : " + userId);
			//int re = resId;
			MyLog.d(TAG, "uploadCollection gameid : " + resId);
			
			RequestParams params = new RequestParams();
			params.put("userid", userId);
			params.put("gameid", resId);
			
			final String url = ConstantURL.COLLECTION_SAVE_SINGLE;
			//String url = "http://192.168.10.131/v4/collection";
			MyLog.d(TAG, "uploadCollection url : " + url);
			
			String token = MySharedPreferences.getString2(VRApplication.getAppContext(),MySharedPreferences.NAME_NOT_CLEAR, Constant.LOGIN_SUCCESS_TOKEN);
			MyLog.d(TAG, "token uploadCollection : " + token);
			RequestUtils.clientToken.addHeader(Constant.STR_X_AUTH_TOKEN,token);
			 
			RequestUtils.clientTokenPost(VRApplication.getAppContext(),url,params,new NetCallBack(){
				
				@Override
						public void onMySuccess(int statusCode, Header[] aheader,
								JSONObject jsonobject) {
							super.onMySuccess(statusCode, aheader, jsonobject);
							MyLog.d(TAG, "uploadCollection onMySuccess statusCode : "
									+ statusCode);
							if(jsonobject == null){
								MyLog.d(TAG, "uploadCollection jsonobject == null");
								return;
							}
							MyLog.d(TAG, "uploadCollection onMySuccess jsonobject : "
									+ jsonobject.toString());
							
							if (statusCode == 200) {
								ServerErrorMsg msg = JSON.parseObject(jsonobject.toString(), ServerErrorMsg.class);
								if(msg.getError().equals(Constant.SERVER_SUCCESS_KEY_E000)){
									//MyToast.showMessage(context,R.string.collection_success);
									//DownloadTask task = new DownloadTask(userId);
									//task.start();
									
									MyLog.d(TAG, "Favorite addition completed");
									return;
								}
							}
							//MyToast.showMessage(context, R.string.collection_failed);
							MyLog.d(TAG, "Favorite addition failed");
						}
				
				@Override
				public void onMyFailure(int statusCode, Header[] headers,
						Throwable throwable, JSONObject errorResponse) {
					super.onMyFailure(statusCode, headers, throwable, errorResponse);
					NetRequestManager.isCommonErr(statusCode, errorResponse, VRApplication.getAppContext(),url);
				}
				

			});
		}
		
		/**
		 * 取消收藏
		 */
		private void ColloctionDel(){
			//int gameId = gameItem.getId();
			MyLog.d(TAG, "cancelCollection actorId : " + resId);
			
			/*RequestParams params = new RequestParams();
			params.put("userid", userId);
			params.put("gameid", gameId);*/
			
			final String url = ConstantURL.COLLECTION_CANCEL_SINGLE + "gameid=" + resId + "&userid=" + userId;
			MyLog.d(TAG, "cancelCollection url : " + url);
			
			String token = MySharedPreferences.getString2(VRApplication.getAppContext(),MySharedPreferences.NAME_NOT_CLEAR, Constant.LOGIN_SUCCESS_TOKEN);
			MyLog.d(TAG, "token cancelCollection : " + token);
			RequestUtils.clientToken.addHeader(Constant.STR_X_AUTH_TOKEN,token);
			
			RequestUtils.clientTokenPut(VRApplication.getAppContext(), url, /*params, */new NetCallBack(){
				@Override
				public void onMyStart() {
					super.onMyStart();
					MyLog.d(TAG, "cancelCollection onMyStart...");
				}
				
				@Override
				public void onMySuccess(int statusCode, Header[] aheader,
						JSONObject jsonobject) {
					super.onMySuccess(statusCode, aheader, jsonobject);
					
					if(jsonobject == null){
						MyLog.e(TAG, "cancelCollection onMySuccess jsonobject == null");
						return;
					}
					MyLog.d(TAG, "cancelCollection onMySuccess jsonobject : " + jsonobject.toString());
				}
				
				@Override
				public void onMyFailure(int statusCode, Header[] headers,
						Throwable throwable, JSONObject errorResponse) {
					super.onMyFailure(statusCode, headers, throwable, errorResponse);
					NetRequestManager.isCommonErr(statusCode, errorResponse, VRApplication.getAppContext(),url);
				}
				

			});
		}
	}
}
